define([ "app", "jquery", "bootstrapJs","md5", "ecb","angularRadial","radial","highcharts","highcharts-ng",
         "directives/DatetimePicker",
         "services/UserService",
         "resources/OrgResource",
		 "resources/UserResource",
		 "resources/CompanyDetailResource",
		 "services/MessageBox",
		 "directives/common/OrgUserPickerConference",
		 "directives/common/OrgTreeView",
		 "services/TipsService",
		 "services/BaseService"
		],
		function(app) {

	var deps = [ "$scope", "$state", "$window",  "$location",
			"$stateParams", "MenuService", "UserService","OrgResource", "UserResource","CompanyDetailResource","MessageBox","TipsService","BaseService"];

	function controller($scope, $state, $window, $location, $stateParams, MenuService, UserService,OrgResource, UserResource,CompanyDetailResource,MessageBox,TipsService,BaseService) {
		
		// 通过go传递参数-主键ID 
		var keyId=$stateParams.keyId;
		// JSON字符串转JSON对象
		//var str = '{"json":json0,"success":true}';
		//var json = eval("("+str+")");
		$scope.user ={};
		$scope.downLoadDate = strToDate(new Date());
		$scope.user = UserService.getCurrentUser();
		if(keyId==null || keyId==""){
			keyId =$scope.user.currentCompanyCode;
		}
		$scope.dateArrays28=['1', '2', '3', '4', '5', '6','7', '8', '9', '10', '11', '12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28'];
		$scope.dateArrays29=['1', '2', '3', '4', '5', '6','7', '8', '9', '10', '11', '12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29'];
		$scope.dateArrays30=['1', '2', '3', '4', '5', '6','7', '8', '9', '10', '11', '12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30'];
		$scope.dateArrays31=['1', '2', '3', '4', '5', '6','7', '8', '9', '10', '11', '12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'];
		
		$scope.dateArrays=[];
		$scope.resultLine=[];
		// 初始化数据
		init($scope,CompanyDetailResource,keyId);
		
		$scope.changeLoadDate =function($date){
	    	var month=$scope.currentMonth;
			var currentDate=new Date().format("yyyy-MM-dd");
			var currentYear =parseInt(currentDate.substring(0,4));
			var downLoadDate =$scope.downLoadDate;
			var url ='restful/company/downLoadExcel?keyId='+keyId+"&currentYear="+currentYear+"&currentMonth="+$scope.currentMonth+"&downLoadDate="+convertDate(downLoadDate);
	    	$scope.downLoadUrl=url;
		}
		/**
		 * type 前一月:减少 2：后一月
		 */
		$scope.changeDate =function (type){
			
			$scope.resultLine=[];
			var month=$scope.currentMonth;
			var currentYear =$scope.currentYear;
			if(type==1){
				if(month==1){
					$scope.currentYear=currentYear-1
					$scope.currentMonth=12;
				}else{
					$scope.currentMonth--;
					
				}
				
			}
			if(type ==2){
				if(month==12){
					$scope.currentYear=currentYear+1
					$scope.currentMonth=1;
				}else{
					$scope.currentMonth++;
				}
				
			}
			
			if($scope.currentMonth==2){
				// 闰年 2月29天
				if(isLeapYear(currentYear)){
					$scope.dateArrays=$scope.dateArrays29;
				}else{
					$scope.dateArrays=$scope.dateArrays28;
				}
			}else if($scope.currentMonth==1 || $scope.currentMonth==3 || $scope.currentMonth==5 || $scope.currentMonth==7 
					|| $scope.currentMonth==8 || $scope.currentMonth==10 || $scope.currentMonth==12){
				$scope.dateArrays=$scope.dateArrays31;
			}else{
				$scope.dateArrays=$scope.dateArrays30;
			}
			nameDesc="畅会通"+$scope.currentYear+"年"+$scope.currentMonth+"月消费曲线图";
			var downLoadDate =$scope.downLoadDate;
			var url ='restful/company/downLoadExcel?keyId='+keyId+"&currentYear="+currentYear+"&currentMonth="+$scope.currentMonth+"&downLoadDate="+convertDate(downLoadDate);
	    	$scope.downLoadUrl=url;
	    	
			var result =[];
			// 根据当前时间获取每天消费记录
			CompanyDetailResource.queryConsumeDataLine(keyId,$scope.currentYear,$scope.currentMonth).success(function(data){
				
				
				for(var i=0;i<data.length;i++){
					result.push(data[i]);
				}
				$scope.resultLine=result;
				// 刷新图表
				refreshGraphic($scope,nameDesc);
	        });
			
		};
    };
    
    
    function strToDate(str) {
		return new Date(str).format("yyyy-MM-dd");
	}
	
	
	function convertDate(dateStr) {
    	var timeStamp = null;
    	if(dateStr) {
    		var newDateStr = dateStr + ' 00:00:00';
    		newDateStr = newDateStr.replace(/-/g,"/");
    		var date = new Date(newDateStr);
    		timeStamp = date.getTime();
    	}
    	return timeStamp;
    }
	
    Date.prototype.format =function(format) {
        var o = {
            "M+" : this.getMonth()+1, //month
		    "d+" : this.getDate(),    //day
		    "h+" : this.getHours(),   //hour
		    "m+" : this.getMinutes(), //minute
		    "s+" : this.getSeconds(), //second
		    "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
		    "S" : this.getMilliseconds() //millisecond
        };
        if(/(y+)/.test(format)) 
        	format=format.replace(RegExp.$1, (this.getFullYear()+"").substr(4- RegExp.$1.length));
        for(var k in o)
        	if(new RegExp("("+ k +")").test(format))
        		format = format.replace(RegExp.$1, RegExp.$1.length==1? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
        return format;
    };
    
    /**
     * 初始化取消报表
     */
    function refreshGraphic($scope,nameDesc){
    	$('#container').highcharts({
			chart: {
	            type: 'line'
	        },
			title: {
	            text: nameDesc,
	            x: -20 //center
	        },
	        subtitle: {
	            text: '',
	            x: -20
	        },
	        xAxis: {
	            categories: $scope.dateArrays
	        },
	        yAxis: {
	            title: {
	                text: '单位：元'
	            },
	            plotLines: [{
	                value: 0,
	                width: 1,
	                color: '#808080'
	            }]
	        },
	        tooltip: {
	            valueSuffix: '元'
	        },
	        legend: {
	            layout: 'vertical',
	            align: 'right',
	            verticalAlign: 'middle',
	            borderWidth: 0
	        },
	        series: [{
	            name: '当天消费',
	            data: $scope.resultLine
	        }]
	    });
    }
    function init($scope,CompanyDetailResource,keyId){
    	
    	var currentDate=new Date().format("yyyy-MM-dd");
		var currentYear =parseInt(currentDate.substring(0,4));
		var month =parseInt(currentDate.substring(5,8));
		$scope.currentMonth=month;
		$scope.currentYear=currentYear;
		var downLoadDate =$scope.downLoadDate;
    	// 初始化下载链接
    	var url ='restful/company/downLoadExcel?keyId='+keyId+"&currentYear="+currentYear+"&currentMonth="+$scope.currentMonth+"&downLoadDate="+convertDate(downLoadDate);;
    	$scope.downLoadUrl=url;
		
		
		//账号余额
		var radialObj1 = radialIndicator('#indicatorContainer1');
		// 当月消费
		var radialObj2 = radialIndicator('#indicatorContainer2');
		// 当天消费
		var radialObj3 = radialIndicator('#indicatorContainer3');
		
		radialObj1.option('displayNumber',false);
		radialObj1.option('barColor','#2cb1f5');
		radialObj1.option('barWidth',15);
		radialObj1.option('radius',45);
		radialObj1.option('frameTime',1);
		radialObj1.option('frameNum',500);
		
		
		
		radialObj2.option('displayNumber',false);
		radialObj2.option('barColor','#ebba23');
		radialObj2.option('barWidth',15);
		radialObj2.option('radius',45);
		radialObj2.option('frameTime',1);
		radialObj2.option('frameNum',500);
		
		
		radialObj3.option('displayNumber',false);
		radialObj3.option('barColor','#383838');
		radialObj3.option('barWidth',15);
		radialObj3.option('radius',45);
		radialObj3.option('frameTime',1);
		radialObj3.option('frameNum',500);
		
		if(month==2){
			// 闰年 2月29天
			if(isLeapYear(currentYear)){
				$scope.dateArrays=$scope.dateArrays29;
			}else{
				$scope.dateArrays=$scope.dateArrays28;
			}
		}else if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12){
			$scope.dateArrays=$scope.dateArrays31;
		}else{
			$scope.dateArrays=$scope.dateArrays30;
		}
		
		// 获取消费信息,生成圆形进度
		CompanyDetailResource.queryAccountInfo(keyId).success(function(data){

			// 设置累计消费
			$scope.theCumulativeConsume=parseFloat(data.theCumulativeConsume).toFixed(2);
			//账号余额
			$scope.accountBalance=parseFloat(data.accountBalance).toFixed(2);
			radialObj1.animate($scope.accountBalance); 
			radialObj1.option('maxValue',data.accountBalance+data.theCumulativeConsume);
			
			// 当月消费
			$scope.theMonthConsume=parseFloat(data.theMonthConsume).toFixed(2);
			radialObj2.animate($scope.theMonthConsume); 
			radialObj2.option('maxValue',data.accountBalance+data.theCumulativeConsume);
			
			// 当天消费
			$scope.theDateConsume=parseFloat(data.theDateConsume).toFixed(2);
			//radialObj3.value($scope.theDateConsume);
			radialObj3.animate($scope.theDateConsume);
			radialObj3.option('maxValue',data.accountBalance+data.theCumulativeConsume);
			
        });
		
		// 获取公司信息 
		CompanyDetailResource.queryCompanyByCode(keyId).success(function(data){
			$scope.company=data;
        });
		
		var nameDesc ="畅会通"+$scope.currentYear+"年"+$scope.currentMonth+"月消费曲线图";
		// 根据当前时间获取每天消费记录
		CompanyDetailResource.queryConsumeDataLine(keyId,$scope.currentYear,$scope.currentMonth).success(function(data){
			
			var result =[];
			for(var i=0;i<data.length;i++){
				result.push(data[i]);
			}
			$scope.resultLine=result;
			refreshGraphic($scope,nameDesc);
        });
    }
    


	function isLeapYear(Year) {

		if (((Year % 4) == 0) && ((Year % 100) != 0) || ((Year % 400) == 0)) {
			return (true);
		} else {
			return (false);
		}
	} 

    
    Date.prototype.format =function(format) {
        var o = {
            "M+" : this.getMonth()+1, //month
		    "d+" : this.getDate(),    //day
		    "h+" : this.getHours(),   //hour
		    "m+" : this.getMinutes(), //minute
		    "s+" : this.getSeconds(), //second
		    "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
		    "S" : this.getMilliseconds() //millisecond
        };
        if(/(y+)/.test(format)) 
        	format=format.replace(RegExp.$1, (this.getFullYear()+"").substr(4- RegExp.$1.length));
        for(var k in o)
        	if(new RegExp("("+ k +")").test(format))
        		format = format.replace(RegExp.$1, RegExp.$1.length==1? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
        return format;
    };
    
	controller.$inject = deps;
	return app.lazy.controller("CompanyDetailController", controller);
});
